package com.game.sdk.pay;

import java.util.HashMap;
import java.util.Map;

import android.text.TextUtils;
import org.apache.http.util.EncodingUtils;

import android.R;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.game.sdk.util.DialogUtil;
import com.game.sdk.util.MResource;
import com.game.sdk.util.NetworkImpl;
import com.game.sdk.util.Util;

/**
 * @author lingguihua
 * @time 2016/09/08
 * @说明： 这个activity要接受两个参数，一个是mem_id(也就是账号，或者是账号的变体),另外一个是token(也就是密码，或者说密码的变体)
 * */
public class ChargeActivityForWap extends Activity implements OnClickListener {
	private static final String TAG = "ChargeActivityForWap";
	private WebView wv;
	private TextView tv_back, tv_charge_title;
	private ImageView iv_cancel;
	private String url, title;
	private String mem_id, token;
	private double amount;
	private String toast;
	private StringBuffer postDate = new StringBuffer("");

	public static OnPaymentListener paymentListener;// 充值接口监听
	public boolean isPaySus = false;// 支付jar包的回执
	public static final int REQUEST_CODE = 200;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(MResource.getIdByName(getApplication(), "layout",
				"sdk_float_web"));
		// setContentView(R.layout.sdk_float_web);
		Intent intent = getIntent();
		url = intent.getStringExtra("url");
		title = intent.getStringExtra("title");
		wv = (WebView) findViewById(MResource.getIdByName(getApplication(),
				"id", "wv_content"));
		// wv = (WebView) findViewById(R.id.wv_content);
		tv_back = (TextView) findViewById(MResource.getIdByName(
				getApplication(), "id", "tv_back"));
		// tv_back = (TextView) findViewById(R.id.tv_back);
		iv_cancel = (ImageView) findViewById(MResource.getIdByName(
				getApplication(), "id", "iv_cancel"));
		// iv_cancel = (ImageView) findViewById(R.id.iv_cancel);

		tv_charge_title = (TextView) findViewById(MResource.getIdByName(
				getApplication(), "id", "tv_charge_title"));
		// tv_charge_title = (TextView) findViewById(R.id.tv_charge_title);
		tv_charge_title.setText(title);
		tv_back.setOnClickListener(this);
		iv_cancel.setOnClickListener(this);

		postDate.append("mem_id=").append(mem_id).append("&token=")
				.append(token);
		wv.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				wv.postUrl(url,
						EncodingUtils.getBytes(postDate.toString(), "UTF-8"));
				return true;
			}
		});

		wv.getSettings().setJavaScriptEnabled(true);
		wv.getSettings().setLoadsImagesAutomatically(true);
		wv.getSettings().setAppCacheEnabled(false);
		wv.getSettings().setDomStorageEnabled(true);
		wv.getSettings().setDefaultTextEncodingName("UTF-8");
		AndroidJSInterfaceForWeb js = new AndroidJSInterfaceForWeb();
		js.ctx = this;
		wv.addJavascriptInterface(js, "android");

		wv.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				if (!DialogUtil.isShowing()) {
					DialogUtil.showDialog(ChargeActivityForWap.this, "正在加载...");
				}
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				webviewCompat(wv);
				try {
					DialogUtil.dismissDialog();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});
		wv.setWebChromeClient(new WebChromeClient());
		webviewCompat(wv);
		wv.postUrl(url, EncodingUtils.getBytes(postDate.toString(), "UTF-8"));

	}

	@Override
	public void onClick(View v) {

		if (v.getId() == tv_back.getId()) {
			if (wv.canGoBack()) {
				wv.goBack();
				return;
			}
			handleResult();
		}
		if (v.getId() == iv_cancel.getId()) {
			handleResult();
		}
	}

	/**
	 * 一些版本特性操作，需要适配、
	 * 
	 * @date 6/3
	 * @param mWebView
	 * @reason 在微蓝项目的时候遇到了 返回键 之后 wv显示错误信息
	 * */
	private void webviewCompat(WebView mWebView) {
		if (NetworkImpl.isNetWorkConneted(mWebView.getContext())) {
			mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
		} else {
			mWebView.getSettings().setCacheMode(
					WebSettings.LOAD_CACHE_ELSE_NETWORK);
		}
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		handleResult();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.finish();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE) {
			if (data != null) {
				amount = data.getDoubleExtra("amount", 0);
				boolean sus = data.getBooleanExtra("result", false);
				toast = data.getStringExtra("attach");
				isPaySus = sus;
			}
			handleResult();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void handleResult() {
		if(isPaySus){
			PaymentCallbackInfo payInfo = new PaymentCallbackInfo();
			payInfo.msg = toast==null?"支付成功":toast;
			payInfo.money = amount;
			paymentListener.paymentSuccess(payInfo);
		}else{
			PaymentErrorMsg errorMsg = new PaymentErrorMsg();
			errorMsg.code = -1;
			errorMsg.money = amount;
			errorMsg.msg = toast==null?"支付失败":toast;
			paymentListener.paymentError(errorMsg);
		}
		this.finish();
	}
}
